package com.controller;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.bean.User;
import com.bean.UserInfo;
import com.dao.UserInfoMapper;
import com.dao.UserMapper;
import com.service.*;

/**
 * 根据映射路径选择不同的方法,基本都与帐号的操作有关
 * @author hhh
 *
 */
@Controller
public class UserController {
	@Autowired
	private UserMapper userDao;
	@Autowired
	private UserInfoMapper userInfoDao ;
	
	@RequestMapping(value="/login")//登录
	public void login(String name, String password, HttpServletRequest req, HttpServletResponse resp,HttpSession session)
			throws IOException, SQLException {
		User user = (User) userDao.get(name);
		UserInfo userInfo = (UserInfo) userInfoDao.get(name);
		if (password != null && user != null && MD5.stringMD5(password).equals(user.getPassword())) {//校验密码
			session.setAttribute("pass", userInfo);
			resp.getWriter().write("true");
		} else {
			resp.getWriter().write("false");
		}
	}
	
	@RequestMapping(value="/logincheck")//登录状态验证
	public void logincheck(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, SQLException {
		HttpSession session = req.getSession();
		PrintWriter out=resp.getWriter();
		if (session.getAttribute("pass")!=null) {//
			out.write("true");
		} else {
			out.write("false");
		}
	}

	@RequestMapping("/exit")
	public void exit(HttpServletRequest req, HttpServletResponse resp,HttpSession session) throws IOException {
		session.invalidate();
		resp.sendRedirect("http://localhost:8080/SSMFrame/login.htm");

	}

	//根据submit参数的值选择不同管理员操作
	@RequestMapping("/jsp/admin")
	public void checkAdmin(@RequestParam String name, String submit, HttpServletRequest req,HttpServletResponse resp) throws IOException {
		HttpSession session=req.getSession();
			PrintWriter out=resp.getWriter();
		if("no".equals(submit)){
		User admin=(User) userDao.get(name);
		//判断优先级,ajax传入
		if(admin.getPriority()>8){
			session.setAttribute("priority", admin);
			out.write("true");
			}else
				out.write("false");
				return;
			
		//搜索用户
		}else if("search".equals(submit)){
			List<User> users=userDao.getAll(name);//按name模糊查询所有的User对象
			ArrayList<User> al=new ArrayList<User>(users);
			session.setAttribute("result", al);
		}else if("delete".equals(submit)&&!"hxd".equals(name)){
			userDao.delete(name);
		}
		resp.sendRedirect("admin.jsp");
	}
	
	@RequestMapping("/recall")//找回密码
	public void recall(@RequestParam String name,String email,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		UserInfo userInfo=(UserInfo)userInfoDao.get(name);
		PrintWriter out=resp.getWriter();
		String mail=userInfo.getEmail();
		User user=(User)userDao.get(name);
		String pass=user.getPassword();
		if(pass.equals(email)){
			resp.sendRedirect("inner/setPassword.jsp");
		}else{
			if(mail.equals(email)){
			SendMessage sm=new SendMessage();
			String message="<h1>健康规划中心<h1><br/> </p>亲爱的用户  "+name+
					",如果您遗忘了密码,请  "
					+ "<a href='http://localhost:8080/SSMFrame/recall.do?name="+name+"&email="+pass+"'>点击此处</a>前往设置新密码";
			sm.doSendHtmlEmail("Manager", message, email);
			out.write("true");
			}else{
				out.write("false");
			}
		resp.sendRedirect("recallPassword.htm");
		}
	}
	
	@RequestMapping("jsp/setPassword")//修改密码
	public void setPass(@RequestParam String password,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		HttpSession session=req.getSession();
		User user=(User)session.getAttribute("pass2");
		if(user!=null){
			password=MD5.stringMD5(password);
			user.setPassword(password);
			userDao.update(user);
			session.removeAttribute("pass2");
		}
		resp.sendRedirect("inner/setPassword.jsp");
	}
	@RequestMapping("jsp/update")//修改个人属性
	public void update(@RequestParam String name, String age,String email,
			String sex,String height,String weight,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		HttpSession session=req.getSession();
		UserInfo userInfo=(UserInfo)session.getAttribute("pass");
		userInfo.setAge(Integer.parseInt(age));
		userInfo.setEmail(email);
		userInfo.setHeight(Double.parseDouble(height));
		userInfo.setWeight(Double.parseDouble(weight));
		if("男".equals(sex)||"女".equals(sex))
			userInfo.setSex(sex);
		userInfoDao.update(userInfo);
			session.setAttribute("pass", userInfo);
			session.setAttribute("msg", "修改成功!");
		resp.sendRedirect("privy.jsp");
	}
	
	
	@RequestMapping(value="/jsp/upload",method=RequestMethod.POST)//上传图片
	  public void upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{  
        //获取解析器  
        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        //判断是否是文件  
        if(resolver.isMultipart(request)){  
            //进行转换  
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request);  
            //获取所有文件名称  
            Iterator<String> it = multiRequest.getFileNames();  
            while(it.hasNext()){  
                //根据文件名称取文件  
                MultipartFile file = multiRequest.getFile(it.next());  
                UserInfo ui=(UserInfo)(request.getSession().getAttribute("pass"));
                String localPath = "E:/eclipse/workspacespring//WebContent/img/portrait/" + ui.getName()+".jpg";  
                File newFile = new File(localPath);  
                //上传的文件写入到指定的文件中  
                file.transferTo(newFile); 
                request.getSession().setAttribute("msg", "上传成功!");
            } 
		                  response.sendRedirect("jsp/privy.jsp");
		  }
}
	
	@RequestMapping("/register")
	public void register(@RequestParam String name, String password, String age, String sex, String email,
			String height, String weight, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		if (userDao.get(name) == null) {
			User user = new User(name, MD5.stringMD5(password));
			userDao.add(user);
			UserInfo userInfo = new UserInfo(user.getId(), name, Integer.parseInt(age), sex, email,
					Double.parseDouble(height), Double.parseDouble(weight));
			userInfoDao.add(userInfo);
			resp.getWriter().write("true");
		} else {
			resp.getWriter().write("false");
		}
		resp.sendRedirect("http://localhost:8080/SSMFrame/login.htm");
	}
	
	@RequestMapping("/checkRegister") // ajax检查注册
	@ResponseBody
	public void checkRegister(@RequestParam String name, HttpServletResponse req) {
		req.setContentType("text/html");
		PrintWriter write = null;
		try {
			write = req.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		User user = (User)userDao.get(name);
		if (user == null)
			write.print("true");
		else
			write.print("false");
		write.close();
	}
}